package com.working.libcommon.util

import android.graphics.Bitmap
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.working.libcommon.exts.toBase64
import com.working.libcommon.exts.toBitmap
import java.io.IOException
import java.lang.reflect.Type


internal val CHAR_SEQUENCE_JSON_ADAPTER: JsonAdapter<String?> =
    object : JsonAdapter<String?>() {
        @Throws(IOException::class)
        override fun fromJson(reader: JsonReader): String? {
            return reader.nextString()
        }

        @Throws(IOException::class)
        override fun toJson(writer: JsonWriter, value: String?) {
            writer.value(value)
        }

        override fun toString(): String {
            return "JsonAdapter(CharSequence)"
        }
    }

internal val BITMAP_JSON_ADAPTER: JsonAdapter<Bitmap?> =
    object : JsonAdapter<Bitmap?>() {
        @Throws(IOException::class)
        override fun fromJson(reader: JsonReader): Bitmap? {
            return reader.nextString().toBitmap()
        }

        @Throws(IOException::class)
        override fun toJson(writer: JsonWriter, value: Bitmap?) {
            writer.value(value?.toBase64())
        }

        override fun toString(): String {
            return "JsonAdapter(Bitmap)"
        }
    }

class SupplementJsonAdapterFactory : JsonAdapter.Factory {
    override fun create(
        type: Type,
        annotations: MutableSet<out Annotation>,
        moshi: Moshi
    ): JsonAdapter<*>? {
        if (annotations.isNotEmpty()) return null
        if (type === CharSequence::class.java) return CHAR_SEQUENCE_JSON_ADAPTER
        if (type === Bitmap::class.java) return BITMAP_JSON_ADAPTER
        return null
    }
}